package cn.gailvlun.gll.net.interceptor

import cn.gailvlun.gll.event.AuthEvent
import cn.gailvlun.gll.net.token.CustomUtils
import cn.gailvlun.gll.net.token.RefreshTokenStateEnum
import cn.gailvlun.gll.net.token.TokenStateEnum
import cn.gailvlun.gll.util.LogUtil
import okhttp3.Interceptor
import okhttp3.Response
import org.greenrobot.eventbus.EventBus


const val DETAIL: String = "Signature has expired."
const val AUTH = "Authorization"
const val RETRY_COUNTS = 2

class TokenInterceptor2(
        var mAuthInfo: MutableMap<Int, String>
) : Interceptor {

    override fun intercept(chain: Interceptor.Chain): Response? {
        var request = chain.request()
        val orderKey = CustomUtils.authInfo(request)
        if (mAuthInfo.containsKey(orderKey)) { 

            
            val (tokenStateEnum, response) = TokenStateEnum.getTokenState(chain)
            when (tokenStateEnum) {
                TokenStateEnum.NONE -> {

                    return null
                }
                TokenStateEnum.UNAUTHORIZED -> {
                    RefreshTokenStateEnum.isTokenExpired = true

                }
                TokenStateEnum.OTHERS -> {
                    return response
                }
            }

            
            LogUtil.d("beforeRefreshToken, time: " + System.currentTimeMillis() + ", chain: " + chain)
            when (RefreshTokenStateEnum.refreshTokenLocked()) {
                RefreshTokenStateEnum.OK -> {
                    return chain.proceed(RefreshTokenStateEnum.getNewRequest(response?.request()!!))
                }
                RefreshTokenStateEnum.REFRESH_FAILURE -> {
                    LogUtil.d("invalid, time: " + System.currentTimeMillis() + ", chain: " + chain)
                    EventBus.getDefault().post(AuthEvent())
                    return null
                }
                RefreshTokenStateEnum.OTHERS -> {
                    return response
                }


            }
        } else {
            return chain.proceed(chain.request())
        }
    }


}